﻿using System;
using System.Collections.Generic;
using System.Data;
using CoreSoft.Frame.Entity;
using CoreSoft.Frame.Entity.http;
using FERROU8API.Pub;
using U8Login;
using UFIDA.U8.MomServiceCommon;
using UFSoft.U8.Framework.ContextSrv;
using UFSoft.U8.Framework.DBConnection;
using System.Text;

namespace FERROU8API.Plugin
{
    /// <summary>
    /// 生产订单
    /// </summary>
    public class Rd09Plugin
    {
        //private readonly string _ip = ConfigurationManager.AppSettings["WmsIP"] + "Moorderapi";
        public static string constr = "";
        private string url = "";

         
       
        public static string getSyncDbConnection(string server , string user, string psd, string db)
        {
            return "Server = " + server + ";User = " + user + "; Pwd = " + psd + ";Database = " + db;
        }

        public bool Delete_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {
                MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

                //从上下文获取U8Login对象
                U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
                if (login != null)
                    constr = login.UFDataConnstringForNet;
                if (string.IsNullOrEmpty(constr))
                {
                    errMsg = "Rd09Plugin，Delete_After，获取连接串失败";
                    DebugWriteLog.WriteLine("Rd09Plugin", "Delete_After", errMsg);
                    return false;
                }

                string accid = login.get_cAcc_Id();
                MSXML2.IXMLDOMNode tmphead = domhead.selectSingleNode("//z:row");
                //string cverifer = tmphead.attributes.getNamedItem("cHandler").nodeValue.ObjToString();//审核人
                //if (string.IsNullOrEmpty(cverifer))//非审核状态
                //{
                //    return true;
                //}
                string ccode = tmphead.attributes.getNamedItem("ccode").nodeValue.ObjToString();//入库单号
                string id = tmphead.attributes.getNamedItem("id").nodeValue.ObjToString();//入库单号

                //MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;
                //clsLogin login = ctx.U8Login as clsLogin;
                //if (login != null)
                //    constr = login.UFDataConnstringForNet;

                String js;

                js = GetCustJs(accid, ccode, id, 0);
                //不是线边仓直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    DebugWriteLog.WriteLine("Rd08Plugin", "Delete_After", errMsg);
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("Rd08Plugin", "Delete_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }


        public bool Update_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {
                MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

                //从上下文获取U8Login对象
                U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
                if (login != null)
                    constr = login.UFDataConnstringForNet;
                if (string.IsNullOrEmpty(constr))
                {
                    errMsg = "Rd09Plugin，Update_After，获取连接串失败";
                    DebugWriteLog.WriteLine("Rd09Plugin", "Update_After", errMsg);
                    return false;
                }
                
                string accid = login.get_cAcc_Id();
                MSXML2.IXMLDOMNode tmphead = domhead.selectSingleNode("//z:row");
                //string cverifer = tmphead.attributes.getNamedItem("cHandler").nodeValue.ObjToString();//审核人
                //if (string.IsNullOrEmpty(cverifer))//非审核状态
                //{
                //    return true;
                //}
                string ccode = tmphead.attributes.getNamedItem("ccode").nodeValue.ObjToString();//入库单号
                string id = tmphead.attributes.getNamedItem("id").nodeValue.ObjToString();//入库单号

                //MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;
                //clsLogin login = ctx.U8Login as clsLogin;
                //if (login != null)
                //    constr = login.UFDataConnstringForNet;

                String js;
                
                js = GetCustJs(accid, ccode, id, 1);
                //不是线边仓直接返回true
                if (js == "Nopermission")
                {
                    return true;
                }

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    DebugWriteLog.WriteLine("Rd09Plugin", "Update_After", errMsg);
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("Rd09Plugin", "Update_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }

        private string GetCustJs(string accid, string ccode, string id, int operation)
        {
            DebugWriteLog.WriteLine("调拔单下游其他出库单单接口", "ccode", "ccode=" + ccode + ";id=" + id);

            try
            {
                var datatable = Common.GetUrl(constr, accid).Tables[0];
                if (datatable == null)
                {
                    DebugWriteLog.WriteLine("调拔单下游其他出库单单接口", "GetUrl", "Nopermission");
                    return "Nopermission";
                }
                var datarow = datatable.Rows[0];
                if (datatable == null)
                {
                    DebugWriteLog.WriteLine("调拔单下游其他出库单单接口", "GetUrl", "datarow Nopermission");
                    return "Nopermission";
                }
                url = datarow[1] + "receiveMLot";
                
                
                #region SQL代码片段

                //inv.cInvStd 成品规格
                string sql = @"select a.cinvcode,
                            a.cdefine33 as transferid, isnull(ts.cmocode, ts.cdefine31) as mono, isnull(ts.imoseq, ts.cdefine32) as mobody,
                            a.iquantity as count, b.cwhcode as whocode, cBatch as batchcode
                          from  rdrecords09 a  with (nolock)
                           inner join rdrecord09 b with (nolock) on b.id = a.id
                           inner join warehouse w with (nolock) on w.cwhcode = b.cwhcode
						   inner join transvouchs ts with (nolock) on ts.autoid = a.iTrIds 
                           where b.id = '" + id + "' and w.iWHProperty = 1";

                var table = DbHelperSQL.Query(sql, constr, null).Tables[0];
                if (table == null || table.Rows.Count <= 0)
                {
                    DebugWriteLog.WriteLine("调拔单下游其他出库单单接口", "table", " Nopermission");
                    return "Nopermission";
                }
                #endregion

                string modids = string.Empty;

                List<receiveMLot> mlist = new List<receiveMLot>();
                foreach (DataRow item in table.Rows)
                {
                    #region mes原有字段
                    receiveMLot rd08 = new receiveMLot();
                    rd08.mono = item["mono"].ObjToString(); //MoCode 生产订单号码  
                    rd08.mobody = item["mobody"].ObjToString(); //SortSeq 行号  
                    rd08.cinvcode = item["cinvcode"].ObjToString(); //存储编码
                    rd08.batchcode = item["batchcode"].ObjToString(); //物料条码
                    rd08.transferid = item["transferid"].ObjToString(); //调拔申请id  
                    rd08.count = item["count"].ObjToDecimal(); //数量
                    rd08.whocode = item["whocode"].ObjToString();  //仓库编码
                    rd08.stepname = ""; // 工步
                
                    #endregion

                    mlist.Add(rd08);
                }
                DebugWriteLog.WriteLine("其他出库单接口地址:" + url);
                DebugWriteLog.WriteLine("调拔单下游其他出库单单接口", "获取数据：", mlist.ToJson());

                //modids = modids.TrimEnd(',');



                //MESreceiveMLot endOrder = new MESreceiveMLot();
                //endOrder.receiveMLots = mlist;

                ApiRequest req = new ApiRequest();
                req.data = mlist;
                req.orgcode = accid;
                req.primarykey = id.ToString();
                req.operation = operation;

                DebugWriteLog.WriteLine("调拔单下游其他入库单单接口", "抛出参数", req.ToJson());
                return req.ToJson();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

    }
}